#include "custom_table_model.hpp"

CustomTableModel::CustomTableModel(QObject *parent)
    : QAbstractTableModel(parent)
{
  std::cout << "create CustomTableModel instance ......" << std::endl;
}

int CustomTableModel::rowCount(const QModelIndex &parent) const
{
  return table_data.size();
}

int CustomTableModel::columnCount(const QModelIndex &parent) const
{
  return header_titles.size();
}

QVariant CustomTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  if (orientation != Qt::Horizontal)
  {
    return QVariant("only support horizontal orientation");
  }

  switch (role)
  {
  case Qt::TextAlignmentRole:
    return QVariant(Qt::AlignCenter | Qt::AlignVCenter);
  case Qt::DisplayRole:
    return QVariant(QString::fromStdString(header_titles[section]));
  case Qt::BackgroundRole:
    // 设置黑色背景
    return QBrush(Qt::black);
  case Qt::ForegroundRole:
    // 设置白色文字
    return QBrush(Qt::white);
  default:
    return QVariant();
  }
}

QVariant CustomTableModel::data(const QModelIndex &index, int role) const
{
  int n_row = index.row();
  int n_column = index.column();

  switch (role)
  {
  case Qt::TextAlignmentRole:
    return QVariant(Qt::AlignCenter | Qt::AlignVCenter);
  case Qt::DisplayRole:
    return QVariant(QString::fromStdString(table_data[n_row][n_column]));
  default:
    return QVariant();
  }
  return QVariant();
}

void CustomTableModel::clear()
{
  header_titles.clear();
  table_data.clear();
}

void CustomTableModel::setMyHeaders(std::vector<std::string> &headers)
{
  header_titles = headers;
}

void CustomTableModel::addMyRow(std::vector<std::string> &row_data)
{
  table_data.push_back(row_data);
}

void CustomTableModel::removeMyRow()
{
  if (!table_data.empty()) table_data.pop_back();
}
